package com.dragonwu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dragonwu.model.entity.SysUser;
import com.dragonwu.mapper.SysUserMapper;
import com.dragonwu.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @author DragonWu
 * @since 2022-10-06 20:47
 **/
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //查询用户信息
        SysUser user = sysUserMapper.selectOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUserName,username));
        //如果没有查询到用户就抛出异常
        if (Objects.isNull(user)) {
            throw new UsernameNotFoundException("用户名不存在!");
        }
        //查询对应的权限信息和角色信息
        // 这一般需要查询role表和jurisdiction表的权限,这里略过
        List<String> jurisdiction=new ArrayList<>(Arrays.asList("admin","normal","ROLE_manager"));
        //将数据封装到UserDetail返回
        return new LoginUser(user, jurisdiction);
    }
}
